#!/usr/bin/php
<?php
/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

require("bashcommon.php");

$starttime=mtime();

$blog =& LoggerManager::getLogger('bash_updatestats');
$blog->info("Started");
$_log->info("Started");

define('CURRENT_DIR',dirname(__FILE__));
$last_slash = strrpos(CURRENT_DIR, "/");
$postats = TEMP_PATH."/stats";

DEFINE('SCRIPT',CURRENT_DIR.'/msgstats.sh');

if (!file_exists(TEMP_PATH)) {
	createDir(TEMP_PATH);
}

if (!file_exists($postats)) {
	createDir($postats);
}

function addfile(&$array,$index,$file,$prj,$sprj) {
	global $blog;
	if ($array[$index]==null) {
		$array[$index]=array();
	}
	$elem = array("file" => $file,"prj" => $prj,"sprj" => $sprj);
	array_push($array[$index],$elem);
	$blog->debug("Added notification: ".$file->name);
	$blog->debug("List size for $index: ".count($array[$index]));
	$blog->debug("List size: ".count($array));
}

//error_reporting(0);
//ini_set('display_errors', false);
$blog->debug("ROOT_PATH: ".ROOT_PATH);
$blog->debug("SVN_ROOT: ".SVN_ROOT);

$totalfiles=0;
$totalprojects=0;
$totalfailedfiles=0;

$blog->info("Processing");
$_log->info("Processing");

/* GET ACTIVE PROJECT LIST */
$prj = new project;
$prj->status=STATUS_ACTIVE;
$prjlist = $loader->loadListBy($prj,$prj->listByStatus(true));

$teamnotify=array();
$usernotify=array();

foreach ($prjlist as $inprj) {
	$totalprojects+=1;
	$blog->debug("============= PROJECT ".$inprj->id." - ".$inprj->name." =============");
	
	/* GET ACTIVE SUBPROJECT LIST */
	$sprj = new project;
	$sprj->status=STATUS_ACTIVE;
	$sprj->upd="true";
	$sprj->parent=$inprj->id;
	$sprjlist = $loader->loadListBy($sprj,$sprj->listByAny());	

	//debug($sprjlist);
	
	foreach ($sprjlist as $insub) {
		$blog->debug("============= SUBPROJECT ".$insub->id." - ".$insub->name." =============");
		/* GET ACTIVE TEAM LIST */
		$team = new team;
		$teamlist = $loader->loadListBy($team,$team->listByReady($inprj->id,$insub->id,true));
		
		//debug($teamlist);
		
		foreach ($teamlist as $inteam) {
			$blog->debug("============= TEAM ".$inteam->id." - ".$inteam->name. " =============");
			/* GET FILE LIST */
			$file = new files($inprj->id);
			$file->teamid=$inteam->id;
			$file->prjid=$insub->id;
			$filelist = $loader->loadListBy($file,$file->loadfiltered());
			
			//debug($filelist);

			foreach ($filelist as $infile) {
				$totalfiles+=1;
				$blog->debug("============= FILE ".$infile->id." - ".$infile->name." =============");
				$url=$inprj->path . str_replace('$LANG',$inteam->lang,$insub->path);	
				$url .= '/'.$infile->name;
				$filename=$postats.'/'.$infile->name;
				$blog->debug("Get File ".$url);
				for ($i=1;$i<=3;$i++) {
		            try {
						$svn  = new phpsvnclient;
						$svn->setRespository(SVN_ROOT);
						$text = $svn->getFile($url);
						if (($out = fopen($filename, 'w'))) {
							fwrite($out,$text);
							fclose($out);
						} else {
							$blog->error("Unable to open file for writing. [$filename]");
						}
		            } catch (Exception $e) {
		            	$blog->error($svn->errNro);
		                $blog->error($e);
		            }
					if (file_exists($filename)) {
						break;
					}
					$blog->debug("Try get file again: ".$i);
				}
				
				if (file_exists($filename)) {
					$blog->debug("Processing file ".$filename);	
					
					/* CALL MSGFMT */
					$blog->debug("MSGFMT");
					$in = exec(SCRIPT." ".$filename." ".$postats);				
					/* REMOVE THE FILE */
					unlink($filename);
					unlink(CURRENT_DIR."/messages.mo");
					/* READ GENERATED STATS */
					$stats = explode(";", $in);
					$blog->debug("Read Stats [".count($stats)."]");
					$notify = false;
					$mark = false;
					if (count($stats)==3) {
						$translated=$stats[0];
						$untranslated=$stats[1];
						$fuzzy=$stats[2];
						$control = $fuzzy + $untranslated;

						$blog->debug("Old Stats => fuzzy: $infile->fuzzy - untranslated: $infile->untranslated - translated: $infile->translated");
						$blog->debug("Current => fuzzy: $fuzzy - untranslated: $untranslated - translated: $translated");													
						
						/* UPDATE FILE */
						if ($fuzzy > $infile->fuzzy or $untranslated > $infile->untranslated) {
							$notify = true;							
						} else if ($control>0 and ($infile->fuzzy==0 and $infile->untranslated==0)) {
							$notify = true;
							$mark=true;
						}
						
						$infile->translated=$translated;
						$infile->fuzzy=$fuzzy;
						$infile->untranslated=$untranslated;
						$loader->execute($infile->stats());
						
						if (($control > 0 and $infile->statusid == FILE_STATUS_DONE)) {
							$blog->debug("File completed changed.");
							$infile->statusid = FILE_STATUS_LOCKED;
							$infile->comment = s("Messages updated from POT",$inteam->lang);
							$infile->stamp=util::hashcode($infile->id);
							$loader->execute($infile->update());
							
							$his = new history($inprj->id);
							$his->statusid=$infile->statusid;
							$his->fileid=$infile->id;
							$his->userid=BOT_USER;
							$his->comment=$infile->comment;
							$loader->save($his);
							if ($infile->userid!=null and $infile->userid!="") {
								addfile($usernotify,$infile->userid,$infile,$inprj,$insub);	
							} else {
								addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);	
							}
						} elseif ($notify and ($infile->statusid == FILE_STATUS_TRANS or $infile->statusid == FILE_STATUS_CHKPND)) {
							$blog->debug("Translation phase changed.");
							if ($infile->statusid==FILE_STATUS_CHKPND) {
								$infile->statusid = FILE_STATUS_LOCKED;
								$infile->comment = s("Messages updated from POT",$inteam->lang);
								$infile->stamp=util::hashcode($infile->id);
								$loader->execute($infile->update());
							}
							$his = new history($inprj->id);
							$his->statusid=$infile->statusid;
							$his->fileid=$infile->id;
							$his->userid=BOT_USER;
							$his->comment=s("Messages updated from POT",$inteam->lang);
							$loader->save($his);
							//addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
							if ($infile->userid!=null and $infile->userid!="") {
								addfile($usernotify,$infile->userid,$infile,$inprj,$insub);	
							} else {
								addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
							}
						} elseif ($notify and $infile->statusid == FILE_STATUS_PROOF) {
							$blog->debug("Proofreading phase changed.");
							
							$his = new history($inprj->id);
							$his->statusid=$infile->statusid;
							$his->fileid=$infile->id;
							$his->userid=BOT_USER;
							$his->comment=s("Messages updated from POT",$inteam->lang);
							$loader->save($his);
							//addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
							if ($infile->userid2!=null and $infile->userid2!="") {
								addfile($usernotify,$infile->userid2,$infile,$inprj,$insub);	
							} else {
								addfile($teamnotify,$infile->teamid,$infile, $inprj,$insub);
							}							
						}
						$blog->debug("============= FINISHED FILE ".$infile->name. " =============");						
					} else {
						$totalfailedfiles+=1;
						$blog->warn("FAILED PROCESSING STATS ".$infile->name);
					}
				} else {
					$totalfailedfiles+=1;
					$blog->warn("FAILED GETTING FILE ".$infile->name);
				}
			}
			$blog->debug("============= FINISHED TEAM ".$inteam->id." =============");
		}
		$blog->debug("============= FINISHED SUBPROJECT ".$insub->id." =============");	
	}

	/* UPDATE PROJECT */
	$blog->debug("============= FINISHED PROJECT ".$inprj->id." =============");
	$inprj->statsupdated=util::now();
	$loader->execute($inprj->stats());	

}

if (DISABLE_STATS_NOTIFY != "true") {
	$blog->info("Notify coordinators [".count($teamnotify)."]");
	$_log->info("Notify coordinators [".count($teamnotify)."]");
	foreach ($teamnotify as $teamid => $elem) {
		$u = new user;
		$u->teamid=$teamid;
		$u->groupid=GROUP_COORD;
		$u->status=STATUS_ACTIVE;
		$list = $loader->loadListBy($u,$u->listByFilters());
		
		foreach ($list as $user) {
			mailNotifyStatUpdate($user,$elem);	
		}
	}
	
	$blog->info("Notify users [".count($usernotify)."]");
	$_log->info("Notify users [".count($usernotify)."]");
	foreach ($usernotify as $userid => $elem) {
		$u = new user;
		$u->userid=$userid;
		$loader->get($u);
		mailNotifyStatUpdate($u,$elem);	
	}
} else {
	$blog->info("Notification disabled");
	$_log->info("Notification disabled");
}

$db->close();
$endtime=mtime();
$blog->info("Finished");
$_log->info("Finished");
$blog->info("============= * =============");
$_log->info("============= * =============");
$statstext = "Projects processed: ".$totalprojects."\nFiles processed: ".$totalfiles." of which ".$totalfailedfiles." failed.";
$blog->info($statstext);
$_log->info($statstext);
$blog->info("Process time: ".sec2hms($endtime-$starttime,true));
$_log->info("Process time: ".sec2hms($endtime-$starttime,true));
LoggerManager::shutdown();
?>